package setting

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"shop-common/library/config"
	"shop-common/library/db"
	"shop-common/library/env"
	"shop-common/library/logger"
	"shop-common/library/variables"
)

var Config *config.Application

func init() {
	_, b, _, _ := runtime.Caller(0)
	Root := filepath.Join(filepath.Dir(b), "../../../../shop-admin/config/")

	bytes, err := ioutil.ReadFile(Root + fmt.Sprintf("/application-%s.yaml", "dev"))
	if err != nil {
		panic(err)
	}
	if err = yaml.Unmarshal(bytes, &Config); err != nil {
		panic(err)
	}
}

func NewTestEnv() {
	variables.AppDebug = Config.Debug
	variables.MysqlSetting = Config.Mysql
	variables.RedisSetting = Config.Redis
	variables.LoggerSetting = Config.Logger
	variables.ZoneSetting = Config.Zone
	os.Setenv(env.EnvName, Config.Server.Env)
	if variables.MysqlSetting != nil && variables.MysqlSetting.Host != "" {
		_, err := db.NewMySQLWithGORM(variables.MysqlSetting)
		if err != nil {
			panic(err)
		}
		variables.GormDB = db.DB
	}

	if variables.RedisSetting != nil && variables.RedisSetting.Addr != "" {
		redisClient, err := db.NewRedis(variables.RedisSetting)
		if err != nil {
			panic(err)
		}
		variables.RedisConn = redisClient
	}

	if variables.LoggerSetting == nil {
		panic("invalid logger address or nil pointer dereference")
	}

	l, err := logger.NewLogger(variables.LoggerSetting.RootPath, variables.LoggerSetting.Level, "test")
	if err != nil {
		panic("invalid logger address or nil pointer dereference")
	}
	variables.Logger = l
}
